package com.example.demo.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.example.demo.bean.UserBean;
import com.example.demo.bean.dto.UserLoginDTO;
import com.example.demo.bean.vo.UserLoginByPassVO;
import com.example.demo.entity.UsersInfo;
import com.example.demo.result.Result;
import com.example.demo.service.IUserLoginService;
import com.example.demo.service.IUsersInfoService;
import com.example.demo.service.RedisService;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/*
 * @Author:大力王
 * @Date:2024/4/6-06-14:04
 * 开始了
 */
@Api(tags = "redis接口")
@RestController
@RequestMapping("/Redis")
public class RedisController {
    @Resource
    private RedisService redisService;

    @Resource
    private IUserLoginService userLoginService;

    @Resource
    private IUsersInfoService usersInfoService;

    @PostMapping("/value/{key}")
    public void setValue(@PathVariable String key, Object value) {
        System.err.println(key+":"+value);
        redisService.setValue(key,value);
    }

    @GetMapping("/value/{key}")
    public Object getValue(@PathVariable String key, UserLoginByPassVO newUserBean) {
//        先查询redis里面有没有用户信息
        if (redisService.getValue(key) != null) {
            return redisService.getValue(key);
        }else {
            //        如果redis里面没有用户信息，就查询数据库
            UserBean userBean = new UserBean();
            BeanUtil.copyProperties(newUserBean,userBean);
            UserLoginDTO userLoginDTO = userLoginService.userLoginByPass(userBean);
            redisService.setValue(key, "我是从数据库里面查询出来的数据"+userLoginDTO.getUsername());
        }
        return 1;
    }

    @DeleteMapping("/value/{key}")
    public void deleteValue(@PathVariable String key) {
        redisService.deleteValue(key);
    }

   @GetMapping("/getUserInfoV2")
   @SaCheckLogin
   @ApiOperation( value = "获取用户信息2.0")
   @ApiOperationSupport( author = "言浠")
    public Result getUserInfoV2(){
        //1、通过token获取id
        Integer id = StpUtil.getLoginIdAsInt();
        UsersInfo usersInfo = usersInfoService.findById(id);
        return Result.success(usersInfo);
    }
}
